<?php

declare(strict_types=1);

namespace Plugin\Attractions\AttractionManagement\Repository;

use App\Repository\IRepository;
use Hyperf\Collection\Arr;
use Hyperf\Collection\Collection;
use Hyperf\Database\Model\Builder;
use Plugin\Attractions\AttractionManagement\Model\AttractionUserBooking;

class AttractionUserBookingRepository extends IRepository
{
    public function __construct(protected readonly AttractionUserBooking $model, protected readonly AttractionUserTouristBookingRepository $touristBookingRepository) {}

    public function handleSearch(Builder $query, array $params): Builder
    {
        return $query
            ->when(Arr::get($params, 'userId'), static function (Builder $query, $user_id) {
                $query->where('user_id', $user_id);
            })
            ->when(Arr::get($params, 'infoId'), static function (Builder $query, $info_id) {
                $query->where('info_id', $info_id);
            })
            ->when(Arr::get($params, 'bookingDay'), static function (Builder $query, $booking_day) {
                $query->whereDate('booking_day', $booking_day);
            })
            ->when(Arr::get($params, 'bookingTime'), static function (Builder $query, $booking_time) {
                $query->where('booking_time', $booking_time);
            })
            ->when(Arr::get($params, 'status'), static function (Builder $query, $status) {
                $query->where('status', $status);
            });
    }

    public function list(array $params = []): Collection
    {
        return $this->perQuery($this->getQuery(), $params)
            ->with(['user:id,username', 'tourist', 'info:id,title'])
            ->get(['id', 'user_id as userId', 'info_id as infoId', 'booking_day as bookingDay', 'booking_time as bookingTime', 'status']);
    }

    public function showListPage(array $params = []): array
    {
        $page = intval(Arr::get($params, 'page', 1));
        $pageSize = intval(Arr::get($params, 'pageSize', 20));
        return $this->perQuery($this->getQuery(), $params)
            ->with(['user:id,username', 'tourist', 'info:id,title'])
            ->simplePaginate($pageSize, ['id', 'user_id as userId', 'info_id as infoId', 'booking_day as bookingDay', 'booking_time as bookingTime', 'status'], 'page', $page)
            ->items();
    }

    public function deleteByUser(array $ids)
    {
        $bookingIds = $this->getQuery()->whereIn('user_id', $ids)->pluck('id');
        if (!empty($bookingIds)) {
            $this->touristBookingRepository->getQuery()
                ->whereIn('booking_id', $bookingIds)
                ->delete();
        }
        return $this->deleteById($bookingIds);
    }
}
